<template>
	<view class="content" style="padding-top: 100rpx;">
        <view class="header-div">
             <view class="header-info">
               购物车 <view class="header-tip">（共{{ chooseShop.length }}件）</view>
             </view>
             <view
               :class="isEdit? 'cart-setting  green' : 'cart-setting  blue'" 
               @click="isEdit = !isEdit"
             >
               {{isEdit? '完成' : '管理'}}
             </view>
        </view>
		<block v-if="showPage">
		<view v-if="chooseShop.length === 0 && isLoading === false" style="margin-top:120px">
		      <image class="emptyDataOfCouponImg" src="../../static/shop/coupon_empty.png" />
		      <view class="emptyDataOfCouponTip">
				  <view style="margin: 20rpx 0rpx;">暂无商品</view>
		        <van-button
		          plain
		          type="info"
		          @click="goHome"
		        >去看看</van-button>
		      </view>
		</view>
		<block v-if="chooseShop.length>0">
		<view style="width: 690rpx;margin-left: 30rpx; margin-bottom: 130rpx;padding-bottom: 1rpx;">
		<shop-card
		      v-for="(item, index) in chooseShop"
		      :key="index"
		      :dataObj="item"
		      :isLoading="isLoading"
		      @update="update"
			  @updateNumber="updateNumber"
			  @hanldeUpdataCar="hanldeUpdataCar"
		></shop-card>
		</view>
		</block>
		</block>
		<van-submit-bar
		  :disabled="removeDisabled"
		  :price="totalPrice"
		  :label='label'
		  :button-text="buttonText"
		  @submit="onClickButton"
		  :tip="true"
		  :safe-area-inset-bottom="false"
		>
		  <view class="fiexd-box"><van-checkbox :value="selectAll" @change="allChange">全选</van-checkbox></view> 
		</van-submit-bar>
		<ComponentDialog  @getPhoneOk="init" @cancle="handleClickCanclePhone" title="申请获取手机号" tips="授权手机号后方可使用小程序!" :show="showDialogPhone"></ComponentDialog>
		<u-popup :mask-close-able="false" border-radius="54" mode="center" width="550rpx" height="300rpx"  v-model="showDialogUuid">
					<view class="content-title" >请先授权登录？</view>
					<view class="content-text">不登录无法正常体验！</view>
					<view class="btn-div">
						<!-- <navigator class="btn-cancle" open-type="exit" target="miniProgram">取消</navigator> -->
						<view class="btn-cancle" @click="handleClickCancleUuid">取消</view>
								<view class="line-xian"></view>
						<button @click="bindgetuser"  class="content-button"   type="success">确定</button>
					</view>
		 </u-popup>
	</view>
</template>

<script>
	import api from '../../untils/api.js'
	import ComponentDialog from '../dialog.vue'
	import shopCard from "../../components/shop-card.vue";
	export default {
		components: {
		    shopCard,
			ComponentDialog,
		  },
		data(){
			return{
				showDialogPhone:false,
				showDialogUuid:false,
				isEdit:false,
				removeDisabled:true,
				chooseShop:[],
				isLoading:false,
				selectAll:false,
				totalPrice:0,
				label:"合计：",
				selectedId:[],
				buttonText:"结算",
				showPage:false,
			}
		},
		 watch: {
			 isEdit: function(newValue){
				 if(newValue){
					   this.buttonText="删除"
					   this.label=""
					   this.totalPrice=null
					this.refreshChoose()
				 }
				 else {
					 this.label="合计："
					 this.totalPrice=0
					 this.refreshChoose()
				 }
			 }
		  },
		  onShow() {
		  		this.judge();
				this.isEdit=false;
		  },
		  onShareAppMessage(res) {
		     return {
		       title: "氢启健康商城",
		       path: `/pages/index/index`
		     }
		   },
		methods:{
		     async judge(){
				 this.openid=uni.getStorageSync("openid")
				 this.phone=uni.getStorageSync("phone")
				 if(uni.getStorageSync("uUID")){
				 	 if(uni.getStorageSync("phone")){
				 	    await this.init();
				 	   this.refreshChoose();
				 	 }
				 	 else {
				 	 	this.showDialogPhone=true
				 	 	uni.hideTabBar()
				 	 }
				   }
				   else {
				 	this.showDialogUuid=true
				 	uni.hideTabBar()  
				   }
			 },
			handleClickCancleUuid(){
				this.showDialogUuid=false
				uni.showTabBar()
				uni.switchTab({
					url:"../index/index"
				})
			},
			bindgetuser(){
			uni.getUserProfile({desc:"信息将用于服务",lang:"zh_CN"}).then((res)=>{
					  if(res[1]){
						    			   uni.setStorageSync("userInfo",res[1].userInfo)
						    			   let userinfo=res[1].userInfo
						    			 userinfo.openId=uni.getStorageSync("openid")
						    			 userinfo.signature=res[1].signature
						    	    userinfo.encryptedData=res[1].encryptedData
						    		 userinfo.iv=res[1].iv
									 userinfo.key="ZHQQ_SM"
						    		 console.log(userinfo)
						    		api.register(JSON.stringify(userinfo)).then((res)=>{
						    			  uni.showTabBar()
						    		      this.showDialogUuid=false
										  this.showPage=true;
						    	 }).catch((res)=>{
						    					  })
						            }else {
						    								  uni.showToast({
						    								    title: '拒绝授权将无法正常使用哦',
						    								    icon: 'none',
						    								    duration: 2000
						    								  })
															   this.showPage=true;
						    							  }
						    			}) 
			},
			handleClickCanclePhone(){
				this.showDialogPhone=false
				uni.showTabBar()
				 this.showPage=true;
			},
		   async hanldeUpdataCar(data){
				console.log(data)
				this.chooseShop.forEach((item)=>{
					if(item.id===data.id){
						item.count=data.count
						item.model=data.model
						item.model.specificationsValue=JSON.stringify(item.model.specificationsValue);
					}
				});
			   try {
			     await api.SM_SHOPPING_CART_UPDATE(JSON.stringify(this.chooseShop));
			   } catch (error) {
			     
			   } finally {	
				// await this.init();
				this.refreshChoose()
			   }
			},
		   async	onClickButton(){
				if(this.isEdit){
					      const arr = this.chooseShop.filter((item) => {
					        let step = 0;
					        for (const index of this.selectedId) {
					          if (item.id === index.id) {
					            step = 1;
					          }
					        }
					        if (step !== 1) {
					          return item;
					        }
					      });
					      this.totalCost = 0;
					      try {
					        await api.SM_SHOPPING_CART_UPDATE(JSON.stringify(arr));
					      } catch (error) {
					        
					      } finally {
					       await this.init();
							this.refreshChoose();
					      }
				}
				else {
					this.chooseShop.forEach((item)=>{
						if(item.count>=item.model.buyLimit&&item.model.buyLimit!=0){
							item.count=item.model.buyLimit
						}
					});
					 api.SM_SHOPPING_CART_UPDATE(JSON.stringify(this.chooseShop)).then((res)=>{
						 if(res.data.header.result_code==0){
							 var obj={nowPage: 1, pageSize: 9999, startRecord: 0, parameters: {}, condition: {oredCriteria: [[]]}}
							  api.SM_SHOPPING_CART_LIST(JSON.stringify(obj)).then((res)=>{
							 	  this.chooseShop=res.data.body.exhibitDatas.filter(item=>item.model.stock>0);
								  this.chooseShop.forEach((item)=>{
									  this.selectedId.forEach((it)=>{
										 if(it.model.id==item.model.id){
											 it.id=item.id
										 } 
									  })
								  })
								  console.log(this.selectedId);
								  uni.navigateTo({
								  	url:`../confirmOrder/confirmOrder?list=${JSON.stringify(this.selectedId)}&orderFrom=1`
								  })
							 })
							 
						 }
					 })
				}
			},
		   async updateNumber(number,id){
				this.chooseShop.forEach((item)=>{
					if(item.id==id){
						item.count=Number(number)
					}
				})
				try {
				  await api.SM_SHOPPING_CART_UPDATE(JSON.stringify(this.chooseShop));
				} catch (error) {
				  
				} finally {	
				 
				   this.refreshChoose()
				}
			},
			update(id){
				this.chooseShop.map((item)=>{
					if(item.id==id){
						item.isChecked=!item.isChecked
					}
				})
				this.refreshChoose()
			},
			 // 刷新状态
			refreshChoose() {
				if (this.chooseShop.length === 0) {
					uni.removeTabBarBadge({index:1})
				  this.selectAll = false;
				  this.totalPrice=0;
				  if(this.isEdit===false){
					  this.buttonText = `结算`
					  this.removeDisabled=true
				  }
				  else {
					  this.buttonText="删除"
					  this.removeDisabled=true
				  }
				}
				if(this.chooseShop.length>0){
					uni.setTabBarBadge({
					  index: 1,
					  text: String(this.chooseShop.length),
					});
						this.selectAll=false
						this.selectedId = [];
						let total = 0;
						var flag=true;
						this.chooseShop.map((item) => {
						  if (item.isChecked === true) {
						    this.selectedId.push(item);
							total = item.model.price * item.count + total;
						  } else if (!item.isChecked) {
						    flag=false
						  }
						});
						if(flag){
							this.selectAll=true
						}
						if(this.selectedId.length===0){
							this.removeDisabled=true
						}
						else {
							this.removeDisabled=false
						}
						if(this.isEdit===false) {
							this.totalPrice = total*100;
						    if(this.selectedId.length>0){
								this.buttonText = `结算(${this.selectedId.length})`
						      }
						     else {
							    this.buttonText = `结算` 
						       }
					       }
					   }
			    },
			goHome(){
				uni.switchTab({
				  url: '/pages/index/index'
				})
			},
		  async	init(){
			  this.showPage=false;
			  uni.showLoading({
			  	title:"加载中"
			  });
				var obj={nowPage: 1, pageSize: 9999, startRecord: 0, parameters: {}, condition: {oredCriteria: [[]]}}
				await api.SM_SHOPPING_CART_LIST(JSON.stringify(obj)).then((res)=>{
					  this.chooseShop=res.data.body.exhibitDatas.filter(item=>item.model.stock>0);
					  if(this.chooseShop.length>0){
						  this.chooseShop.forEach((item)=>{
							    if(item.model.stock>item.model.buyLimit&&item.count>=item.model.buyLimit&&item.model.buyLimit!=0){
							    	item.count=item.model.buyLimit
							    }
								if(item.count>=item.model.stock&&item.model.stock<item.model.buyLimit&&item.model.buyLimit!=0){
									item.count=item.model.stock
								}
								if(item.model.buyLimit==0&&item.count>=item.model.stock){
									item.count=item.model.stock
								}
						  		item.isChecked=false
						  		item.model.img=item.model.img.replace(/(^\s*)|(\s*$)/g, "");
						  })
					  }
				})
				console.log(this.chooseShop)
				this.showPage=true;
				uni.hideLoading();
			},
			allChange(e){
				this.selectAll=e.detail
				if(e.detail){
					if(this.chooseShop.length>0){
						this.chooseShop.forEach((item)=>{
							item.isChecked=true
						})
						this.refreshChoose();
						this.removeDisabled=false;
					}
					else {
						this.removeDisabled=true;
					}
				}
				else {
					this.chooseShop.forEach((item)=>{
						item.isChecked=false
					})
					this.refreshChoose()
					this.removeDisabled=true
				}
			}
		},
	}
</script>

<style lang="scss" scoped>
	.line-xian{
		width: 1rpx;
		height: 100%;
		background: #a3a3a3;
	}
	.btn-cancle{
		width: 50%;
		height: 100rpx;
		line-height: 100rpx;
		text-align: center;
	}
	.btn-div{
		display: flex;
		flex-direction: row;
		align-items: center;
		width: 100%;
		height: 100rpx;
	}
	.content-title{
		width: 100%;
		text-align: center;
		padding-top: 40rpx;
		margin-bottom: 40rpx;
		font-size: 36rpx;
		color: #000000;
		font-weight: 500;
	}
	.content-text{
		width: 100%;
		text-align: center;
		font-size: 28rpx;
		color: #303133;
		padding-bottom: 30rpx;
		border-bottom: 1rpx solid #a3a3a3;
	}
	 button::after { border: none; }
	.content-button{
	  width: 50%;
	  height: 100rpx;
	  line-height: 100rpx;
	  text-align: center;
	  font-size: 30rpx;
	  color: #303133;
	  background-color:#FFFFFF;
	}
	.fiexd-box{
		position: fixed;
		left: 30rpx;
		bottom: 30rpx;
	}
	.content {
		width: 100vw;
		min-height: 100vh;
		background: rgb(245,247,249);
	}
	.emptyDataOfCouponTip {
	  margin-top: 10px 0px;
	  width: 100%;
	  text-align: center;
	  margin-left: 50%;
	  color: #969799;
	  transform: translateX(-50%);
	  font-size: 14px;
	}
	.emptyDataOfCouponImg{
		 width: 238px;
		  height: 120px;
		  margin-left: 50%;
		  transform: translateX(-50%);
	}
	.cart-setting {
	      width: 15vw;
	      height: 7.5vw;
	      color: #fff;
	      display: flex;
	      align-items: center;
	      justify-content: center;
	      border-radius: 3vw;
	      font-size: 3.8vw;
	    }
	    .blue {
	      background: #4797ff;
	    }
	    .green {
	      background: #43b4b6;
	    }
	.header-tip{
		font-weight: 500;
		        font-size: 4vw;
		        color: #999;
				display: inline-block;
	}
	.header-info{
		font-size: 5vw;
		color: #333;
		font-weight: bold;
	}
    .header-div{
		display: flex;
		    justify-content: space-between;
		    position: fixed;
		    top: 0;
		    left: 0;
		    width: 100vw;
		    height: 15vw;
		    padding: 4vw;
		    background: #f5f7f9;
		    z-index: 100;
	}
</style>
